package com.ustc.hewei.nettyrpc2_0.zookeeper.register;

import com.ustc.hewei.nettyrpc2_0.common.enumeration.RpcError;
import com.ustc.hewei.nettyrpc2_0.common.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
* @description: 将服务注册到服务端本地的map集合中，以便之后客户端的调用
* @author hewei
* @date 2022/7/26 19:08
* @version 1.0
*/

@Slf4j
public abstract class DefaultServiceRegister implements ServiceRegister {
    private final ConcurrentHashMap<String, Object> objectMap = new ConcurrentHashMap<>();

    public int port;

    @Override
    public void register(Object obj, String serviceName, int weight) {
        if (obj != null) {
            objectMap.put(serviceName, obj);
        }
    }

    @Override
    public void unregister(String serviceName) throws Exception {
        objectMap.remove(serviceName);
    }

    public Object getServiceObject(String serviceName) {
        Object obj = objectMap.get(serviceName);
        if (obj == null) {
            log.error("找不到服务 {}", serviceName);
            throw new RpcException(RpcError.UNFOUNDED_SERVICE);
        }
        return obj;
    }
}
